package com.ys.controller.api.finance;

import com.bo.dto.NameValueDto;
import com.ys.config.MenuId;
import com.ys.entity.finance.TcwEntryApply;
import com.ys.entity.sys.YsCol;
import com.ys.service.finance.TcwEntryApplyService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.PdfService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 入账申请单
 */
@Controller
@RequestMapping("/api/inter/tcwEntryApply")
public class ApiInterTcwEntryApplyController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwEntryApplyController.class);

    @Autowired
    private CommonApiService<TcwEntryApply> commonApiService;

    @Autowired
    private TcwEntryApplyService tcwEntryApplyService;

    @Autowired
    private YspTaskService yspTaskService;


    @Autowired
    private PdfService pdfService;


    //菜单id
    private Long menuId = MenuId.TCW_EntryApply;

    //权限字符
    private final String PERMISSIONS_VIEW = "tcwEntryApply:view";
    private final String PERMISSIONS_ADD = "tcwEntryApply:add";
    private final String PERMISSIONS_DY = "tcwEntryApply:exportdy";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwEntryApply setSeachSql(TcwEntryApply cond, String conditions){

        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间

                .addLeftJoin("TB_CompanyBankInfo CB ON CB.Id = A.CompanyBankInfoId ")//公司银行账户管理表
                .addField("CB.Vid AS vid")//账号编码
                .addField("CB.Vyhzhmc AS vyhzhmc")//付款账号名称
                .addField("CB.Vkhh AS vkhh")//付款开户行

                .addLeftJoin("TCW_EntryApplyItem S ON S.Pbid = A.Bid ")//子表
                .addField("S.EntryAmount AS entryAmount")//付款金额
                .addField("S.Remark AS sRemark")//备注
                .addField("S.AnnexFile AS annexFile")//附件
                .addField("S.ReceiptAnnexFile AS receiptAnnexFile")//发票附件
                .addField("S.Vgsbm AS vgsbm")//运营公司编码

                .addLeftJoin("THR_OperateCompanyApply C ON C.Vgsbm = S.Vgsbm ")//运营公司管理表
                .addField("C.Vgsjc AS vgsjc")//运营公司简称

                .addLeftJoin("TB_BaseInfo T ON T.Bid = S.TransactionTypeBid ")//财务交易类型
                .addField("T.Vremark AS vremark")//交易类型

                .addLeftJoin("TCW_PartnerBankInfo PB ON PB.Id = S.PartnerBankInfoId ")//员工银行账户管理
                .addField("PB.Vid AS pbvid")//合作商账户编码
                .addField("PB.Vyhzh AS pbvyhzh")//合作商银行账号
                .addField("PB.PartnerName AS partnerName")//合作商名称

                .setStatus(1)


                //排序
        .setOrderby("A.Bid DESC");

        //查询条件
        String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
        if (nameLinked != null){
            cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
        }


        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwEntryApply cond,String conditions
    ){
        try {
            cond = setSeachSql(cond,conditions);
            LayuiTableVoJA setList = commonApiService.searchLay(cond);
            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwEntryApply cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond,conditions);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcwEntryApply> util = new ExportExcelUtils<>(new TcwEntryApply());
            String toFilePath = util.exportExcel(listData, listField, "入账申请单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwEntryApplyService.add(params,menuId);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcwEntryApplyService.update(params,menuId);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 删除
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tcwEntryApplyService.del(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 删除列表
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toDelByItem")
    @ResponseBody
    public R toDelByItem(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            //删除
            for (int i = 0; i < idList.size(); i++) {
                tcwEntryApplyService.toDelByItem(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcwEntryApplyService.flowPass(id, ShiroUtils.getUserId());
        } catch (IllegalArgumentException e) {
            //logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        try {
            TcwEntryApply entity = new TcwEntryApply().setId(id).queryFirst();
            return yspTaskService.flowRefuse(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 流转退回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){

        try {
            TcwEntryApply entity = new TcwEntryApply().setId(id).queryFirst();
            return yspTaskService.flowInit(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    /**
     * 打印
     */
    @RequiresPermissions(PERMISSIONS_DY)
    @RequestMapping("/exportdy")
    @ResponseBody
    public R exportdy(HttpServletRequest request,@RequestParam Map<String, Object> params) throws Exception{
        String bid = params.get("bid").toString();
        List<Map<String,Object>> infoList = new TcwEntryApply()
                .addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
                .addField("U.DeptName AS deptName")//制单人部门
                .addField("FORMAT(A.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByStr")//创建时间

                .addLeftJoin("TB_CompanyBankInfo CB ON CB.Id = A.CompanyBankInfoId ")//公司银行账户管理表
                .addField("CB.Vid AS vid")//账号编码
                .addField("CB.Vyhzhmc AS vyhzhmc")//付款账号名称
                .addField("CB.Vkhh AS vkhh")//付款开户行

                .addLeftJoin("TCW_EntryApplyItem S ON S.Pbid = A.Bid ")//子表
                .addField("S.EntryAmount AS entryAmount")//付款金额

                .setBid(bid)
                .queryMap();

        if(infoList!=null && infoList.size()>0){
            Map<String,Object> sonByOne = infoList.get(0);

            BigDecimal sonAmountTotal = BigDecimal.ZERO;
            for (Map<String, Object> son : infoList){
                sonAmountTotal = sonAmountTotal.add(new BigDecimal(son.get("entryAmount").toString()));
            }

            String nameStr =  (sonByOne.get("vyhzhmc")!=null ? sonByOne.get("vyhzhmc").toString():"")
                    + "/" + (sonByOne.get("vid")!=null ? sonByOne.get("vid").toString():"")
                    + "/" + (sonByOne.get("vkhh")!=null ? sonByOne.get("vkhh").toString():"");

            List<NameValueDto> listData = new ArrayList<>();
            listData.add(new NameValueDto("单据编号",bid));
            listData.add(new NameValueDto("申请人",sonByOne.get("_ys_createUserName").toString()));
            listData.add(new NameValueDto("申请部门",sonByOne.get("deptName").toString()));
            listData.add(new NameValueDto("收款账号",nameStr));
            listData.add(new NameValueDto("付款账号","合作商账户"));
            listData.add(new NameValueDto("收款类型","合作商付款"));
            listData.add(new NameValueDto("收款金额",sonAmountTotal.toString()));
            listData.add(new NameValueDto("收款说明",sonByOne.get("remark").toString()));
            String url = pdfService.generatePDF(bid,"入账申请单", sonByOne.get("vyhzhmc").toString(), sonByOne.get("createTimeByStr").toString(),listData);
            return R.ok(url);
        }else {
            return R.error("未查询到要导出的数据");
        }


    }




}